package com.zygh.lz.controller.app;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zygh.lz.constant.SystemCon;
import com.zygh.lz.controller.FileUpload;
import com.zygh.lz.dao.*;
import com.zygh.lz.entity.*;
import com.zygh.lz.stapprove.InBean;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.stapprove.ViLog;
import com.zygh.lz.util.DataTime;
import com.zygh.lz.vo.MyUtil;
import com.zygh.lz.vo.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Api(tags = "APP上传APKrenewal", description = "APKrenewal")
@RestController
@Slf4j
public class APKrenewal {

    @Resource
    private OperationMapper operationMapper;
    @Resource
    private GpsMapper gpsMapper;
    @Resource
    private SignMapper signMapper;
    @Resource
    private EquipageMapper equipageMapper;
    @Resource
    private PoliceDataMapper policeDataMapper;
    @Resource
    private IllegalDataMapper illegalDataMapper;


    @ApiOperation("APK更新")
    @GetMapping("renewal")
    @ViLog(logType = "6", module = "APK跟新,版本号查询")
    public ResultBean renewal() {
        String filepath = "C:\\java\\apache-tomcat-8.5.27\\webapps\\";
        //File类型可以是文件也可以是文件夹
        File file = new File(filepath);
        //将该目录下的所有文件放置在一个File类型的数组中
        File[] fileArray = file.listFiles();
        assert fileArray != null;
        if (fileArray.length != 0) {

            //判断是否为文件，如果是就...
            for (File aFileArray : fileArray)
                if (aFileArray.isFile()) {
                    String filename = aFileArray.toString();
                    String str2 = filename.substring(filename.length() - 3, filename.length());
                    if ("apk".equals(str2)) {
                        String substring = filename.substring(41, 45);
                        return ResultUtil.setOK("success", substring);
                    }
                }
        }
        return ResultUtil.setError(SystemCon.RERROR1, "errot", null);
    }


    @PostMapping("deLogin")
    @ViLog(logType = "2", module = "错误日志上传")
    public void deLogin(@RequestBody(required = false) InBean inBean) {
        JSONObject jsonObject = inBean.convertObj(JSONObject.class);
        String log = jsonObject.getString("log");
        FileWriter writer;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String format = formatter.format(new Date());
        String path = "C:/java/jar包/log/" + format + "/";
        File filePath = new File(path);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        String name = format + ".txt";
        try {
            writer = new FileWriter(path + name, true);
            writer.write(log);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @PostMapping("uploadLog")
    @ApiOperation("上传错误日志")
    @ViLog(logType = "6", module = "上传错误日志")
    @Async("asyncServiceExecutor")
    public void uploadLog(String id, String log) {
        Operation operation = new Operation();
        operation.setPoliceId(id);
        operation.setErrorLog(log);
        operation.setErrorCode(DateUtil.now());
        operationMapper.insertSelective(operation);
    }


    @ApiOperation("监测预警")
    @GetMapping("isNormal")
    public String isNormal() {
        //判断如果数字电台最新获取坐标时间超过60分钟，或者当天获取数字电台在线数量小于10台的进行预警
        Equipage equipage = equipageMapper.selectOne(Wrappers.<Equipage>lambdaQuery()
                .eq(Equipage::getType, "数字电台")
                .orderByDesc(Equipage::getUploadTime)
                .last("limit 1"));

        if (DateUtil.between(DateUtil.parseDateTime(equipage.getUploadTime()), new Date(), DateUnit.MINUTE) > 60) {
            log.info("数字电台坐标最新时间超过60分钟，数字电台数量小于10人");
            return "error";
        }


        return "success";
    }

    @ApiOperation("接处警监测预警")
    @GetMapping("JieisNormal")
    public String JieisNormal() {
        //接处警
        PoliceData policeData = policeDataMapper.selectOne(Wrappers.<PoliceData>lambdaQuery()
                .orderByDesc(PoliceData::getJjsj01)
                .last("limit 1"));

        if (DateUtil.between(DateUtil.parseDateTime(policeData.getJjsj01()), new Date(), DateUnit.MINUTE) > 180) {
            log.info("接处警数据最新时间超过3小时，接处警数量小于10人");
            return "error";
        }
        return "success";
    }

    @ApiOperation("违法数据监测预警")
    @GetMapping("illegalIsNormal")
    public String illegalIsNormal() {
        //违法数据
        IllegalData illegalData = illegalDataMapper.selectOne(Wrappers.<IllegalData>lambdaQuery()
                .orderByDesc(IllegalData::getWfsj)
                .last("limit 1"));

        if (DateUtil.between(DateUtil.parseDateTime(illegalData.getWfsj()), new Date(), DateUnit.MINUTE) > 120) {
            log.info("违法数据最新时间超过120分钟，违法数据数量小于10人");
            return "error";
        }
        return "success";
    }

    @ApiOperation("GPS监测预警")
    @GetMapping("gpsIsNormal")
    public String gpsIsNormal() {
        //获取最新获取gps的时间，如果时间和当前时间大于60分钟，或者在线人数小于10人在线就报警
        Gps gps = gpsMapper.selectOne(Wrappers.<Gps>lambdaQuery().orderByDesc(Gps::getGpsTime)
                .last("limit 1"));

        if (DateUtil.between(gps.getGpsTime(), new Date(), DateUnit.MINUTE) > 60) {
            log.info("gps坐标最新时间超过60分钟，签到人数小于10人");
            return "error";
        }
        return "success";
    }

    @ApiOperation("图片测试")
    @GetMapping("testTp")
    public String testTp(String base64)  {
        String s = MyUtil.compressionBase64(base64,0.4f);
        return s;
    }


}
